//
//  AddContentViewController.swift
//  TODOApp
//
//  Created by chenyh on 2018/5/25.
//  Copyright © 2018年 chenyh. All rights reserved.
//

import UIKit

class AddContentViewController: UIViewController {

    @IBOutlet fileprivate weak var titleTF: UITextField!
    
    @IBOutlet fileprivate weak var contentTV: UITextView!
    var homeModel: HomeModel?
    fileprivate var addContentProvider =  AddContentProvider()
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if homeModel != nil {
            titleTF.text = homeModel!.title
            contentTV.text = homeModel!.content
        }
    }
    @IBAction func clickSaveAction(_ sender: Any) {
        guard let title = titleTF.text,!title.isEmpty else {
            print("标题不能为空!")
            return
        }
        guard !contentTV.text.isEmpty else {
            print("内容不能为空!")
            return
        }
        
        if homeModel != nil {
            editTodoItem(title: title, content: contentTV.text)
        }else {
            addTodoItem(title: title, content: contentTV.text)
        }

        
    }
    fileprivate func editTodoItem(title: String,content: String) {
        
        var configuration   = RequestConfiguration()
        configuration.requestType = .put
        let params = ["id": homeModel!.id,"title": title,"content": content] as [String : Any]
       
        configuration.requestParams = params
        
        
        Alamofire.request("http://0.0.0.0:8888/api/v1/home/editTodoItem",
                          method: configuration.requestType,
                          parameters: configuration.requestParams,
                          encoding: configuration.requestEncode,
                          headers:configuration.requestHeaderFormat)
            .responseJSON(queue: DispatchQueue.global(qos: .background), options:        JSONSerialization.ReadingOptions.mutableContainers, completionHandler: { [unowned self] (responseObject) in
                printLog(responseObject.description)
                NetLayerRequestSender.kShowOrHideNetworkActivityIndicator(false)
                
                if let error = responseObject.error {
                    print(error.localizedDescription)
                }
                if let dict = try? JSONSerialization.jsonObject(with: responseObject.data!, options: .mutableContainers) as? Dictionary<String, Any>,let dictValue = dict,let _ = dictValue["status"] as? Int {
                    
                    if dict == nil {
                        return
                    }
                    
                    guard let result = dict!["result"] as? Bool else {
                        return
                    }
                    if result == true {
                        GCD.runOnMainThread {
                            self.navigationController?.popViewController(animated: true)
                        }
                    }
                }
            }).resume()
    }
    fileprivate func addTodoItem(title: String,content: String) {
        var configuration   = RequestConfiguration()
            configuration.requestType = .post
            configuration.requestParams = ["title": title,"content": content]
        Alamofire.request("http://0.0.0.0:8888/api/v1/home/addTodoItem",
                          method: configuration.requestType,
                          parameters: configuration.requestParams,
                          encoding: configuration.requestEncode,
                          headers:configuration.requestHeaderFormat)
            .responseJSON(queue: DispatchQueue.global(qos: .background), options:        JSONSerialization.ReadingOptions.mutableContainers, completionHandler: { [unowned self] (responseObject) in
                printLog(responseObject.description)
                NetLayerRequestSender.kShowOrHideNetworkActivityIndicator(false)
                
                if let error = responseObject.error {
                    print(error.localizedDescription)
                }
                if let dict = try? JSONSerialization.jsonObject(with: responseObject.data!, options: .mutableContainers) as? Dictionary<String, Any>,let dictValue = dict,let _ = dictValue["status"] as? Int {
                    
                    if dict == nil {
                        return
                    }

                    guard let result = dict!["result"] as? Bool else {
                        return
                    }
                    if result == true {
                        GCD.runOnMainThread {
                            self.navigationController?.popViewController(animated: true)
                        }
                    }
                    
                    
                }
            }).resume()
        
    }
    
    
 

    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
